package com.sike.netty.im.client.handler;

import com.sike.netty.im.client.event.CreateGroupEvent;
import com.sike.netty.im.client.event.GroupChatEvent;
import com.sike.netty.im.client.service.BeanFactory;
import com.sike.netty.im.client.service.ClientService;
import com.sike.netty.im.common.command.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 群聊请求 handler
 *
 * @author chenssy
 * @date 2023/09/23
 */
public class GroupChatRequestHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof GroupChatEvent) {
            ClientService clientService = (ClientService) BeanFactory.getServiceBean(ClientService.class);
            // 群聊菜单
            groupChatMenu();

            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String[] lines = scanner.nextLine().split(" ");
                    switch (lines[0]) {
                        case "01":
                            doGroupChat(ctx,lines);
                            break;
                        case "02":
                            clientService.toMainMenu(ctx);
                            return;
                        case "00":
                            clientService.exitLogin(ctx);
                            return;
                    }
                }
            }).start();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 群聊
     * @param ctx
     * @param lines
     */
    private void doGroupChat(ChannelHandlerContext ctx, String[] lines) {
        GroupChatRequestCommand requestCommand = new GroupChatRequestCommand(lines[1],lines[2]);
        Message message = MessageBuilder.buildMessage(requestCommand,null,null);
        ctx.writeAndFlush(message);
    }

    /**
     * 单聊界面
     */
    private void groupChatMenu() {
        System.out.println("|------------------------------------------------------|");
        System.out.println("|                        群聊                           |");
        System.out.println("|群聊指令：01 groupId message                            |");
        System.out.println("|02:返回主菜单                                           |");
        System.out.println("|00:退出登录                                             |");
        System.out.println("|-------------------------------------------------------|");
    }
}
